package org.robot.scm.platform.wxrobot.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

@Slf4j
public class SocketConnector extends WebSocketClient {

    private final ConnectorHandler handler;
    private final String tag;
    private final String ws;

    public SocketConnector(String ws, String tag, ConnectorHandler handler) throws URISyntaxException {
        super(new URI(ws), new Draft_6455());
        this.ws = ws;
        this.tag = tag;
        this.handler = handler;
        setConnectionLostTimeout(0);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("connect {} ... ok", tag);
    }

    @Override
    public void onMessage(String message) {
        JSONObject jsonObject = JSON.parseObject(message);
        Boolean ping = jsonObject.getBoolean("ping");
        if (Objects.nonNull(ping) && ping) {
            return;
        }
        handler.callBack(message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        /*
        if (remote && code == 1006) {
            log.error("{} socket 1006, disconnect", tag);
            return;
        }
        if (remote && code == -1) {
            log.error("{} socket -1, disconnect", tag);
            return;
        }
        if (remote && code == 1002) {
            log.error("{} socket 1002, disconnect", tag);
            return;
        }
         */
        reconnect(ws, tag, handler);
    }

    @Override
    public void onError(Exception e) {
    }

    @Override
    public void addHeader(String key, String value) {
        super.addHeader(key, value);
    }

    /**
     * 重连机制
     */
    public void reconnect(String ws, String tag, ConnectorHandler handler) {
        log.error("{} socket reconnect", tag);
        new Timer().schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                new SocketConnector(ws, tag, handler).connect();
            }
        }, 1000);
    }

}
